package com.example.spring.jpa.ast.operation;


import com.example.spring.jpa.ast.AstNode;

import java.lang.reflect.InvocationTargetException;
import java.util.HashMap;
import java.util.Map;
import java.util.ServiceLoader;

/**
 * @author: orange
 * @create: 2023-07-22 21:46
 * @description: 表达式只有变量和关键字构成，不能继续解析。比如：xxx IS NULL | xxx IS NOT NULL | xxx ISNULL...
 */
public abstract class AstNoDichotomyOperation implements AstOperation, AstGrammar {
    private String sentence;

    private AstNode astNode;

    private static final Map<String, Class<? extends AstNoDichotomyOperation>> operationClass = new HashMap<>();

    static {
        ServiceLoader<AstNoDichotomyOperation> load = ServiceLoader.load(AstNoDichotomyOperation.class);
        for (AstNoDichotomyOperation noDichotomy : load) {
            operationClass.put(noDichotomy.operation(), noDichotomy.getClass());
        }
    }

    @Override
    public AstNode parse() throws Exception {
        return this;
    }

    public static AstNoDichotomyOperation getInstance(String operation)
            throws InstantiationException, IllegalAccessException, NoSuchMethodException, InvocationTargetException {
        Class<? extends AstNoDichotomyOperation> oClass = operationClass.get(operation);
        return oClass.getDeclaredConstructor().newInstance();
    }

    @Override
    public String sentence() {
        return this.sentence;
    }

    public void setSentence(String sentence) {
        this.sentence = sentence;
    }

    @Override
    public AstNode getLeft() {
        return this.astNode;
    }

    @Override
    public AstNode getRight() {
        return null;
    }

    public void setAstNode(AstNode astNode) {
        this.astNode = astNode;
    }
}
